package com.cy.aircompressor.main.home;

import android.Manifest;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.cy.aircompressor.AppManager;
import com.cy.aircompressor.R;
import com.cy.aircompressor.config.AirConfig;
import com.cy.aircompressor.databinding.ActivityBaseContentBinding;
import com.cy.aircompressor.entity.select.SelectDict;
import com.cy.aircompressor.entity.system.SysConfig;
import com.cy.aircompressor.entity.system.UserInfo;
import com.cy.aircompressor.main.home.fragment.v1.MainContentFragment;
import com.cy.aircompressor.main.home.fragment.v2.MainContentFragmentV2;
import com.cy.aircompressor.main.home.viewmodel.MianViewModel;
import com.cy.aircompressor.main.welcome.fragment.LoginFragment;
import com.cy.aircompressor.main.welcome.fragment.SplashFragment;
import com.cy.aircompressor.utils.Jump;
import com.drug.lib.util.DLog;
import com.drug.lib.util.SPManager;
import com.drug.lib.util.ToastUtil;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.net.model.base.Resource;
import com.net.model.base.activity.BaseVMActivity;
import com.net.model.livedatas.LiveDataBus;
import com.net.model.utils.Constant;

import java.util.List;

import me.yokeyword.fragmentation.anim.DefaultVerticalAnimator;
import me.yokeyword.fragmentation.anim.FragmentAnimator;

public class MainContentActivity extends BaseVMActivity<ActivityBaseContentBinding, MianViewModel> {

    private static final String[] REQUESTED_PERMISSIONS = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
    };

    @Override
    protected ActivityBaseContentBinding getViewBinding() {
        return ActivityBaseContentBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        loadRootFragment(R.id.fl_container, SplashFragment.newInstance());
        XXPermissions.with(this).permission(REQUESTED_PERMISSIONS).request(new OnPermissionCallback() {
            @Override
            public void onGranted(List<String> permissions, boolean all) {

            }
        });
    }

    @Override
    public FragmentAnimator onCreateFragmentAnimator() {
        // 设置横向(和安卓4.x动画相同)
        return new DefaultVerticalAnimator();
    }

    // 再点一次退出程序时间设置
    private static final long WAIT_TIME = 2000L;
    private long TOUCH_TIME = 0;

    @Override
    public void onBackPressedSupport() {
        // 如果是 第一个Fragment 则退出app
        if (getTopFragment() instanceof MainContentFragmentV2) {
            if (System.currentTimeMillis() - TOUCH_TIME < WAIT_TIME) {
                AppManager.getAppManager().appExit(mContext);
            } else {
                TOUCH_TIME = System.currentTimeMillis();
                ToastUtil.show("再按一次退出");
            }
        }
    }

    private int isReady;

    private void showMainPage() {
        showLoading();
        isReady = 0;
        mViewModel.currentUserInfo();
        mViewModel.queryConfig();
        mViewModel.compressor();
        mViewModel.compressorPart();
        mViewModel.compressorPoint();

        mViewModel.collectorChannel();
        mViewModel.powerStation();
        mViewModel.sensorRange();
        mViewModel.sensorType();
        getHandler().postDelayed(runnable, 500);
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (isReady >= 5) {
//                MainActivityV2.start(mContext);
//                loadRootFragment(R.id.fl_container, MainContentFragment.newInstance());
                loadRootFragment(R.id.fl_container, MainContentFragmentV2.newInstance());
                getHandler().removeCallbacks(this);
                dismissDialog();
                isReady = 0;
            } else {
                DLog.d("完成准备进度：" + isReady);
                getHandler().postDelayed(this, 200);
            }
        }
    };


    private void showLoginPage() {
        if (findFragment(LoginFragment.class) == null)
            loadRootFragment(R.id.fl_container, LoginFragment.newInstance());

    }

    MaterialDialog materialDialog;

    @Override
    protected void dataChange() {
        LiveDataBus.get(Jump.jumpKey, Jump.class).observe(this, new Observer<Jump>() {
            @Override
            public void onChanged(Jump jump) {
                if (TextUtils.equals(jump.getJumpPage(), LoginFragment.class.getSimpleName())) {
                    showLoginPage();
                } else if (TextUtils.equals(jump.getJumpPage(), MainContentFragmentV2.class.getSimpleName())) {
                    showMainPage();
                }
            }

        });

        LiveDataBus.get("invalid-token", Integer.class).observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                if (integer == Constant.CODE_AUTH_FAIL) {
                    if (materialDialog == null) {
                        materialDialog = new MaterialDialog.Builder(mContext)
                                .title("提示")
                                .content("由于长时间未使用，登陆已失效，请重新登录！")
                                .positiveText("退出登录")
                                .negativeText("退出系统")
                                .canceledOnTouchOutside(false)
                                .contentColor(ContextCompat.getColor(mContext, R.color.white))
                                .titleColor(ContextCompat.getColor(mContext, R.color.white))
                                .backgroundColor(ContextCompat.getColor(mContext, R.color.default_background))
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        AirConfig.get().release();
                                        SPManager.removePassword();
                                        showLoginPage();
                                    }
                                })
                                .onNegative(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        AppManager.getAppManager().appExit(mContext);
                                    }
                                })
                                .show();
                        return;
                    }
                    if (!materialDialog.isShowing())
                        materialDialog.show();

                }
            }

        });

        mViewModel.getSysConfigObservable().observe(this, new Observer<Resource<SysConfig>>() {
            @Override
            public void onChanged(Resource<SysConfig> sysConfigResource) {
                sysConfigResource.handler(new OnCallback<SysConfig>() {
                    @Override
                    public void onSuccess(SysConfig data) {
                        AirConfig.get().updateSysConfig(data);
                        isReady++;
                    }
                });
            }
        });
        mViewModel.getUserInfoObservable().observe(this, new Observer<Resource<UserInfo>>() {
            @Override
            public void onChanged(Resource<UserInfo> userInfoResource) {
                userInfoResource.handler(new OnCallback<UserInfo>() {
                    @Override
                    public void onSuccess(UserInfo data) {
                        AirConfig.get().updateUserInfo(data);
                        isReady++;
                    }
                });

            }
        });


        mViewModel.getPartObservable().observe(this, new Observer<Resource<List<SelectDict>>>() {
            @Override
            public void onChanged(Resource<List<SelectDict>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<List<SelectDict>>() {
                    @Override
                    public void onSuccess(List<SelectDict> data) {
                        AirConfig.get().updateCompressorPart(data);
                        isReady++;
                    }
                });
            }
        });

        mViewModel.getPointObservable().observe(this, new Observer<Resource<List<SelectDict>>>() {
            @Override
            public void onChanged(Resource<List<SelectDict>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<List<SelectDict>>() {
                    @Override
                    public void onSuccess(List<SelectDict> data) {
                        AirConfig.get().updateCompressorPoint(data);
                        isReady++;
                    }
                });
            }
        });
        mViewModel.getCollectorChannelObservable().observe(this, new Observer<Resource<List<SelectDict>>>() {
            @Override
            public void onChanged(Resource<List<SelectDict>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<List<SelectDict>>() {
                    @Override
                    public void onSuccess(List<SelectDict> data) {
                        AirConfig.get().updateCollectorChannels(data);
                    }
                });
            }
        });
        mViewModel.getCompressorObservable().observe(this, new Observer<Resource<List<SelectDict>>>() {
            @Override
            public void onChanged(Resource<List<SelectDict>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<List<SelectDict>>() {
                    @Override
                    public void onSuccess(List<SelectDict> data) {
                        AirConfig.get().updateCompressors(data);
                        isReady++;
                    }
                });
            }
        });
        mViewModel.getPowerStationObservable().observe(this, new Observer<Resource<List<SelectDict>>>() {
            @Override
            public void onChanged(Resource<List<SelectDict>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<List<SelectDict>>() {
                    @Override
                    public void onSuccess(List<SelectDict> data) {
                        AirConfig.get().updatePowerStations(data);
                    }
                });
            }
        });
        mViewModel.getSensorRangeObservable().observe(this, new Observer<Resource<List<SelectDict>>>() {
            @Override
            public void onChanged(Resource<List<SelectDict>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<List<SelectDict>>() {
                    @Override
                    public void onSuccess(List<SelectDict> data) {
                        AirConfig.get().updateSensorRanges(data);
                    }
                });
            }
        });
        mViewModel.getSensorTypeObservable().observe(this, new Observer<Resource<List<SelectDict>>>() {
            @Override
            public void onChanged(Resource<List<SelectDict>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<List<SelectDict>>() {
                    @Override
                    public void onSuccess(List<SelectDict> data) {
                        AirConfig.get().updateSensorTypes(data);
                    }
                });
            }
        });
    }
}
